<template>
  <a-spin class="poi-list" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l" style="display:flex;flex-wrap: wrap;">
        <div style="margin-bottom:5px;">
          <span>站点：</span>
          <a-select
            style="width:160px;margin-right:15px;"
            show-search
            :allowClear="true"
            placeholder="请选择站点"
            v-model="search.locationId"
            @change="handleByQueryCond"
            :filter-option="filterOption"
          >
            <a-select-option v-for="(item, index) in locationListData" :key="index + '-' + item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>产品名称：</span>
          <a-input-search style="width:240px;margin-right:32px" type="text" placeholder="输入产品名称" allowClear v-model="search.productName" @search="handleByQueryCond" />
        </div>
        <div>
          <span>产品上线时间：</span>
          <a-range-picker style="margin-right:15px;" @change="handleByQueryCond" v-model="search.selectDate" />
        </div>
        <div>
          <span>产品分类：</span>
          <a-select style="width:160px" placeholder="请选择状态" v-model="search.isPoi" @change="handleByQueryCond">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">POI</a-select-option>
            <a-select-option value="0">已售卖</a-select-option>
          </a-select>
        </div>
      </div>

      <div class="r" style="width:200px;text-align:right;">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
        <!-- <a-button type="primary" @click="exportList" style="background:#34C025;border-color:#34C025;">导出excel</a-button> -->
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="productList" :scroll="{ x: 900, y: tableHeight }" rowKey="id"> </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;text-align:right;"
        @change="handlePageChange"
      />
    </div>
  </a-spin>
</template>

<script>
import { pointPioProductData, pointLocationList, exportPoiList } from '@/service'
import upload from '@/components/upload/upload'
import { safeDiv, getExcel } from '@/util'
import moment from 'moment'

export default {
  name: 'areaPoiGoodsList',
  data() {
    return {
      moment,
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // table数据查询条件
      search: {
        locationId: undefined,
        isPoi: '',
        selectDate: [],
        productName: ''
      },
      // 产品列表
      productList: [],
      // 主播列表总数据条数
      anchorTotal: 0,
      locationListData: []
    }
  },

  components: {
    upload
  },

  computed: {
    // table配置
    tableColumns() {
      return [
        { title: '站点', width: 200, dataIndex: 'siteName' },
        { title: '套餐名称', width: 200, dataIndex: 'itemName' },
        { title: '产品名称', width: 260, dataIndex: 'productName' },
        { title: '上线时间', width: 200, dataIndex: 'releaseTime' },
        { title: '产品有效期开始时间', width: 200, dataIndex: 'validBeginDate' },
        {
          title: '售卖价',
          width: 150,
          dataIndex: 'salePrice',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        {
          title: '原价',
          width: 150,
          dataIndex: 'originPrice',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        { title: '销量', width: 120, dataIndex: 'totalOrderNum' },
        { title: '退款订单量', width: 120, dataIndex: 'refundOrderNum' },
        { title: '核销订单量', width: 120, dataIndex: 'completeOrderNum' }
      ]
    }
  },

  methods: {
    // 站点列表
    async getLocationList() {
      await pointLocationList({ city: '' }).then((res = []) => {
        this.locationListData = res
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationId, isPoi, selectDate, productName } = this.search

      return {
        pageIndex,
        pageSize,
        locationId,
        isPoi,
        productName,
        releaseTimeStart: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        releaseTimeEnd: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, cashType, releaseTimeStart, releaseTimeEnd, status } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          cashType: cashType || '',
          status: status || '',
          selectDate: releaseTimeStart && releaseTimeEnd ? [moment(Number(releaseTimeStart)), moment(Number(releaseTimeEnd))] : []
          //  selectDate: beginTime ? Number(beginTime) : null,
          //  endTime: endTime ? Number(endTime) : null,
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 获取产品列表
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      pointPioProductData(this.getParams())
        .then((rs) => {
          this.productList = Object.freeze(rs.productStatisticsList) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    // 导出
    exportList() {
      const query = this.getParams()
      exportPoiList(query)
        .then((res) => {
          getExcel(`产品列表${moment(new Date()).format('YY-MM-DD hh:mm:ss')}.xlsx`, res)
        })
        .catch(() => {
          this.$messageSend.error('数据量过大 请重新筛选！')
        })
    }
  },

  mounted() {
    this.getLocationList()
    this.setSearch()
    this.query()
  },

  filters: {
    // 处理分-元
    fenToYuan(val) {
      if (!val) return 0
      return (val / 100).toFixed(2)
    }
  }
}
</script>

<style lang="less" scoped>
.poi-list {
  padding: 16px;
}
</style>
